<?php
namespace app\api\job;
use app\admin\controller\KingAction;
use app\common\model\ApplicationBanker;
use app\common\model\BetsLog;
use app\common\model\GamblerKing;
use app\common\model\GamesLog;
use app\common\model\KingAccountLog;
use app\common\model\KingBalanceLog;
use app\common\model\LotteryPlay;
use app\common\model\LotteryResult;
use app\common\model\Member;
use app\common\model\PlanUserProgramme;
use app\common\model\UserAccount;
use app\common\model\UserAccountLog;
use think\Db;
use think\queue\Job;

class Bets {

    public function fire(Job $job,$data) {
        // 有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone=='success') {
            // 如果任务执行成功， 记得删除任务
            $job->delete();

//            print("<info>Hello Job has been done and deleted"."</info>\n");
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
//                print("<warn>Hello Job has been retried more than 3 times!"."</warn>\n");

                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }
    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectimes = substr($msectime,0,13);
    }

    private function doHelloJob($data)
    {




//        return true;

        Db::startTrans();
        $info=BetsLog::get($data);
        if($info['state']!=1){
            return true;
        }
        $member_list=[];
        $members=Member::all(['status'=>1]);
        foreach($members as $k=>$v){
            $member_list[$v['id']]=$v;
        }
        try{
            $lottery_result = LotteryResult::get(['lottery_id' => $info['lottery_id'], 'round' => $info['round']]);
            if($lottery_result ){

                $info->new_settlement($lottery_result,$member_list);
            }else{
                return false;
            }

            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            d($e->getMessage());
            // 回滚事务
            Db::rollback();
            return false;

        }


    }








}

